package cn.lds.j375.healthexam.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.lds.j375.healthexam.entity.User;
import cn.lds.j375.healthexam.constant.DsHealthConstant;
import cn.lds.j375.healthexam.dto.ResultDTO;
import cn.lds.j375.healthexam.mapper.UserMapper;
import cn.lds.j375.healthexam.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public ResultDTO<User> loginUser(User user) {

        user.setPassword(SecureUtil.md5(user.getPassword()));

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>(new User())
                .eq("mobile_no",user.getMobileNo())
                .eq("password",user.getPassword());

        User loginUser = userMapper.selectOne(queryWrapper);

        if (Objects.isNull(loginUser)){
            return ResultDTO.buildError(DsHealthConstant.UserInfo.LOGIN_EORROR);
        }

        return ResultDTO.buildSuccess(loginUser);
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO regUser(User user) {
        //密码加密
        user.setPassword(SecureUtil.md5(user.getPassword()));

        //计算年龄
        String idNo = user.getIdNo();

        String birthStr = idNo.substring(6, 14);

        DateFormat df = new SimpleDateFormat("yyyyMMdd");

        Date birth = null;
        try {
            birth = df.parse(birthStr);
            //获取档期时间的时间戳
            long now = new Date().getTime();
            //获取生日的时间戳
            long birthTime = birth.getTime();
            //获取年龄
            int age = (int) ((now - birthTime)/1000/60/60/24/365);

            log.info("年龄：{}",age);

            user.setAge(age);

        } catch (ParseException e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }


        int insert = userMapper.insert(user);

        return ResultDTO.buildError();
    }
}
